﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.Data;
using ZBJF.Warranty.Common.Enums.InsuranceOrder;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using ZBJF.Warranty.Common.Enums.SocketEnum;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceWarranty;
using ZBJF.Warranty.Model.ViewModel.Order;
using ZBJF.Warranty.Model.ViewModel.Sellers;
using ZBJF.Warranty.Model.ViewModel.SocketModel;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.CustomerService.Controllers
{
    public class ToBeCreateWorkOrderController :BaseController
    {
        //
        // GET: /InsuranceWarrantyRecordWorkOrder/
        public ActionResult Index()
        {
            return View();
        }
        #region 获取可报案 保单 + JsonResult GetApprovedInsuranceOrder(InsuranceOrderModel model)
        /// <summary>
        /// 获取可报案 保单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetApprovedInsuranceOrder(InsuranceOrderModel model)
        {
            var total = 0;
            var list =
                ServiceFactory.InsuranceOrderServiceInstance.GetPagingList(model, out total)
                    .Include(o => o.InsuranceWarrantyRecord)
                    .AsNoTracking()
                    .ToList()
                    .Select(o => new
                    {
                        o.ID,
                        o.InsuranceCategoryName,
                        o.ProductName,
                        o.UserName,
                        o.UserPhone,
                        o.CertificateNO,
                        o.IMEI,
                        o.SaleVendorName,
                        ServiceStartTime = o.ServiceStartTime.HasValue ? o.ServiceStartTime.Value.ToString("yyyy-MM-dd") : "",
                        ServiceEndTime = o.ServiceEndTime.HasValue ? o.ServiceEndTime.Value.ToString("yyyy-MM-dd") : "",
                        CreateOrderTime = o.CreateOrderTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        o.ThirdOrderNO,
                        o.InsuranceCompany,
                        o.InsuranceCompanyBranch
                    });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 新建报案页面--从新建报案列表的操作列进入 + ActionResult Create(int insuranceOrderId)
        public ActionResult Create(int insuranceOrderId)
        {
            // 有取消报案 的单 可以再次创建报案  验证 TODO
            var list = ServiceFactory.InsuranceWarrantyRecordServiceInstance
                .LoadByInsuranceOrderId(insuranceOrderId)
                .Where(
                    c =>
                        c.Status != (byte) InsuranceWarrantyStatus.Canceled &&
                        c.Status != (byte)InsuranceWarrantyStatus.Refuse).ToList();
            var count = list.LongCount();
            var insuranceWarrantyRecord = count > 0 ? list.FirstOrDefault() : new InsuranceWarrantyRecord();
            if (insuranceWarrantyRecord.InsuranceOrder == null)
                insuranceWarrantyRecord.InsuranceOrder = ServiceFactory.InsuranceOrderServiceInstance.LoadByID(insuranceOrderId);

            var insuranceOrder = insuranceWarrantyRecord.InsuranceOrder;
            var sellerInsuranceProducts =
                ServiceFactory.InsuranceProductsServiceInstance.LoadByID(
                    insuranceOrder.InsuranceProductID.HasValue ? insuranceOrder.InsuranceProductID.Value : 0);
            var limitnum = 3; //sellerInsuranceProducts != null ? sellerInsuranceProducts.ServiceTimes: 0;//限制次数
            var currentTime = DateTime.Now;
            var canCreatedWarranty = insuranceOrder.Effective == true &&
                                    insuranceOrder.OrderStatus == (byte)InsuranceOrderStatus.HadEffective &&
                                     insuranceOrder.ServiceStartTime <= currentTime &&
                                     insuranceOrder.ServiceEndTime >= currentTime &&
                                     (!insuranceOrder.InsuranceWarrantyRecord.Any() ||
                                      insuranceOrder.InsuranceWarrantyRecord.All(
                                          x =>
                                              x.Status == (int)InsuranceWarrantyStatus.Canceled ||
                                              x.Status == (int)InsuranceWarrantyStatus.Refuse) || count <limitnum);
            ViewBag.CanCreatedWarranty = canCreatedWarranty;

            if (string.IsNullOrEmpty(insuranceWarrantyRecord.Reporter))
                insuranceWarrantyRecord.Reporter = insuranceOrder.UserName;

            if (string.IsNullOrEmpty(insuranceWarrantyRecord.ReporterPhone))
                insuranceWarrantyRecord.ReporterPhone = insuranceOrder.UserPhone;

            return View(insuranceWarrantyRecord);
        }
        #endregion
        #region 新建报案、补充案件信息 + ActionResult SaveInsuranceWarrantyRecord(InsuranceWarrantyRecord model)
        /// <summary>
        /// 新建报案、补充案件信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(true)]
        public ActionResult SaveInsuranceWarrantyRecord(InsuranceWarrantyRecord model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };
            if (ModelState.IsValid)
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    try
                    {
                        var entity = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(model.ID);

                        if (entity == null)//新建报案
                        {
                            model.WarrantyRecordNo = CommonMethod.GetTimeStamp();
                            model.CreateTime = DateTime.Now;
                            model.CreateBy = model.LastModifyBy = CurrentUser.UserAccount;
                            model.LastModifyTime = DateTime.Now;
                            model.InsuranceOrder = null;//外键表得置空
                            model.Status = (byte)InsuranceWarrantyStatus.Created;
                            model.SystemServiceUserId = CurrentUser.ID;
                            model.ExpectAccidentDate = DateTime.Now;
                            var resultEntity = ServiceFactory.InsuranceWarrantyRecordServiceInstance.AddEntities(model);
                            responseResult.Success = resultEntity.ID > 0;
                            #region 后记录操作日志
                            var opreateLogs = new OpreateLogs
                            {
                                CreatedTime = DateTime.Now,
                                LogTableName = "InsuranceWarrantyRecord",
                                LogSubject = "新建报案",
                                LogTablePKID = resultEntity.ID,
                                OpreateUserAccount = CurrentUser.UserAccount,
                                OpreateUserName = CurrentUser.UserDisPlayName
                            };
                            var addLogResult = ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, string.Empty, resultEntity, OpreateType.Add);
                            #endregion


                            #region 后记录流程日志
                            InsuranceWarrantyRecordStatus oldStatusInfo = new InsuranceWarrantyRecordStatus { ID = 0, StatusCode = 0, StatusName = "" };
                            InsuranceWarrantyRecordStatus newStatusInfo = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.LoadByStatus((byte)InsuranceWarrantyStatus.Created);
                            WriteProcessLog(oldStatusInfo, newStatusInfo, null, resultEntity.ID);
                            #endregion
                        }
                        else//补充案件信息
                        {
                            model.LastModifyBy = CurrentUser.UserAccount;
                            model.LastModifyTime = DateTime.Now;
                            #region 先记录日志
                            var opreateLogs = new OpreateLogs
                            {
                                CreatedTime = DateTime.Now,
                                LogTableName = "InsuranceWarrantyRecord",
                                LogSubject = "补充案件信息",
                                LogTablePKID = entity.ID,
                                OpreateUserAccount = CurrentUser.UserAccount,
                                OpreateUserName = CurrentUser.UserDisPlayName
                            };
                            var logEntity = new
                            {
                                entity.Reporter,
                                entity.ReporterPhone,
                                entity.ContactName,
                                entity.ContactPhone,
                                entity.CreateTime,
                                entity.ExpectAccidentDate,
                                entity.CityId,
                                entity.ProvinceId,
                                entity.AccidentAddress,
                                entity.AccidentProsess,
                                entity.Remark,
                                entity.LastModifyBy,
                                entity.LastModifyTime
                            };
                            var addLogResult = ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, logEntity, model);
                            #endregion
                            entity.Reporter = model.Reporter;
                            entity.ReporterPhone = model.ReporterPhone;
                            entity.ContactName = model.ContactName;
                            entity.ContactPhone = model.ContactPhone;
                            entity.ExpectAccidentDate = DateTime.Now;
                            entity.CityId = model.CityId;
                            entity.ProvinceId = model.ProvinceId;
                            entity.AccidentAddress = model.AccidentAddress;
                            entity.AccidentProsess = model.AccidentProsess;
                            entity.Remark = model.Remark;
                            entity.LastModifyBy = model.LastModifyBy;
                            entity.LastModifyTime = model.LastModifyTime;
                            responseResult.Success = ServiceFactory.InsuranceWarrantyRecordServiceInstance.UpdateEntities(entity);
                        }
                        ts.Complete();
                    }
                    catch (Exception ex)
                    {
                        responseResult.Message = ex.Message;
                        ts.Dispose();
                    }
                }

            }
            else
            {
                responseResult.Message = "数据校验失败！";
            }
            TempData["ResponseResult"] = responseResult;//新增案件信息（跳转到处理页面）或者是补充案件信息（跳转到补充案件信息页面）
            return responseResult.OpreateType == OpreateType.Add && responseResult.Success ? RedirectToAction("Index") : RedirectToAction("Create", new { id = model.InsuranceOrderId });
        }
        #endregion
        #region 操作流程日志 + void WriteProcessLog(InsuranceWarrantyRecordStatus oldStatusInfo, InsuranceWarrantyRecordStatus newStatusInfo,int? StatusReasonId)
        /// <summary>
        /// 操作流程日志
        /// </summary>
        /// <param name="oldStatusInfo">旧状态信息</param>
        /// <param name="newStatusInfo">新状态信息</param>
        /// <param name="StatusReasonId">状态备注ID</param>
        /// <param name="Id">报案工单ID</param>
        public void WriteProcessLog(InsuranceWarrantyRecordStatus oldStatusInfo, InsuranceWarrantyRecordStatus newStatusInfo, int? StatusReasonId, long Id)
        {
            ProcessLogs log = new ProcessLogs()
            {
                InsuranceWarrantyRecordId = Id,
                BeforeProcessStatusId = oldStatusInfo.ID,
                BeforeProcessStatusCode = oldStatusInfo.StatusCode,
                BeforeProcessStatusName = oldStatusInfo.StatusName,
                ProcessStatusId = newStatusInfo.ID,
                ProcessStatusCode = newStatusInfo.StatusCode,
                ProcessStatusName = newStatusInfo.StatusName,
                CreateTime = DateTime.Now,
                CreateUserId = (int)CurrentUser.ID,
                CreateByName = CurrentUser.UserDisPlayName,
                CreateByAccount = CurrentUser.UserAccount
            };
            if (StatusReasonId.HasValue && StatusReasonId.Value > 0)
            {
                StatusReason reason = ServiceFactory.StatusReasonServiceInstance.LoadEntities(t => t.ID == StatusReasonId.Value).FirstOrDefault();
                if (reason != null)
                {
                    log.ReasonDescribe = reason.ReasonDescribe;
                    log.StatusReasonId = reason.ID;
                }
            }
            log = ServiceFactory.ProcessLogsServiceInstance.AddEntities(log);
            if (log.ID < 1)
            {
                LogHelper.WriteLog(string.Format("修改报案状态保持数据库失败：状态由{0}修改为{1}。", oldStatusInfo.StatusCode, newStatusInfo.StatusCode), LogType.remark);
            }
        }
        #endregion
        public ActionResult CreateNoInsuranceOrderIWR()
        {
            return View();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetSellerInsuranceProducts(SellerInsuranceProductsModel model)
        {
            //model.iDisplayLength = 5;
            var total = 0;
            var list = (from b in ServiceFactory.SellerInsuranceProductsServiceInstance.GetPagingList(model, out total)
                       join a in ServiceFactory.SellerInsuranceProductMappingsServiceInstance.LoadEntities(n=>n.InsuranceProductId>0) 
                       on b.ID equals a.SellerInsuranceProductId into temp
                        from f in temp.DefaultIfEmpty()
                      join d in ServiceFactory.InsuranceProductsServiceInstance.GetInsuranceProductsAll() on f.InsuranceProductId equals d.ID into temp1
                       from e in temp1.DefaultIfEmpty()
                        select new GetSellerInsuranceProductsModel
                       {
                       ProductName=b.ProductName,
                       SellerInsuranceProductId=b.ID,
                       //InsuranceDeviceType = e != null ? e.InsuranceDeviceType : 0,
                      // InsuranceDevice = e != null ? e.InsuranceDevice : 0,
                      // InsuranceProductCategory = e != null ? e.InsuranceProductCategory : 0,
                       CompanyName = b.InsuranceCompany.CompanyName??"",
                       InsuranceCompanyId=b.InsuranceCompanyID.HasValue?b.InsuranceCompanyID.Value:0,
                       ParentCompanyName = b.InsuranceCompany.ParentCompanyName??"",
                       Coverage=e != null ? e.Coverage:0,
                     //  PolicyPeriod = e != null ?e.PolicyPeriod:0,
                       SellersName= b.Sellers.SellersName,
                       InsuranceProductId = e != null?e.ID:0
                       }).ToList();
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 根据承保公司名称获取员工列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSystemUser(string companyName)
        {
            if(string.IsNullOrEmpty(companyName))
                return Json(new ResultModel(false, "参数错误", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            var companyid = ServiceFactory.InsuranceCompanyServiceInstance.LoadEntities(n => n.CompanyName ==companyName).FirstOrDefault().ID;
            var list = ServiceFactory.SystemUserServiceInstance.GetSystemUserAllByInsuranceCompanyId(companyid).ToList().Select(o => new{o.ID,o.UserDisPlayName});
            return Json(new ResultModel(true, "获取成功", CodeStateEnum.Success, list), JsonRequestBehavior.AllowGet);
        }
        #region 根据被保险设备类型ID 获取品牌类型列表 ActionResult GetProductList(long insuranceDeviceId)
        /// <summary>
        /// 根据被保险设备类型ID 获取品牌类型列表
        /// </summary>
        /// <param name="insuranceDeviceId">被保险设备类型ID</param>
        /// <returns></returns>
        public ActionResult GetProductList(long insuranceDeviceId)
        {
            if (insuranceDeviceId==0)
                return Json(new ResultModel(false, "参数错误", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            var list =
                ServiceFactory.ProductBrandsServiceInstance.LoadEntities(n => n.ProductTypeId == insuranceDeviceId)
                    .Select(o => new {o.ID,o.BrandName}).ToList();
            return Json(new ResultModel(true, "获取成功", CodeStateEnum.Success, list), JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 根据品牌类型ID 获取型号列表 ActionResult GetProductModelsList(long brandId)
        /// <summary>
        /// 根据品牌类型ID 获取型号列表
        /// </summary>
        /// <param name="brandId">品牌类型ID</param>
        /// <returns></returns>
        public ActionResult GetProductModelsList(long brandId)
        {
            if (brandId == 0)
                return Json(new ResultModel(false, "参数错误", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            var list = ServiceFactory.ProductModelsServiceInstance.GetProductModel(brandId).Select(o=>new{o.ID,o.ModelName}).ToList();
            return Json(new ResultModel(true, "获取成功", CodeStateEnum.Success, list), JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 根据型号ID 获取型号编码 ActionResult GetProductModelsCode(long modelId)
        /// <summary>
        ///  根据型号ID 获取型号编码
        /// </summary>
        /// <param name="modelId">型号ID</param>
        /// <returns></returns>
        public ActionResult GetProductModelsCode(long modelId)
        {
            if (modelId == 0)
                return Json(new ResultModel(false, "参数错误", CodeStateEnum.Failed), JsonRequestBehavior.AllowGet);
            var entity =
                ServiceFactory.ProductModelsServiceInstance.LoadByID(modelId) ?? null;
            var modelCode = entity != null ? entity.ModelCode : "";
            return Json(new ResultModel(true, "获取成功", CodeStateEnum.Success, modelCode), JsonRequestBehavior.AllowGet);
        }
        #endregion
        #region 保存无保单案件 ActionResult SaveNoInsuranceOrderIWr(InsuranceWarrantyRecord iwRecord)
        /// <summary>
        /// 保存无保单案件
        /// </summary>
        /// <param name="iwRecord"></param>
        /// <returns></returns>
        public ActionResult SaveNoInsuranceOrderIWr(InsuranceWarrantyRecord iwRecord, List<string> insuranceWarrantyRecordContractInfo)
        {
            var responseResult = new ResponseResult();
            var insuranceOrderModel = iwRecord.InsuranceOrder;
            var insuranceOrder = ServiceFactory.InsuranceOrderServiceInstance.LoadByThirdUniqueNumber(insuranceOrderModel.ThirdUniqueNumber);
            var contractInfoServ = ServiceFactory.InsuranceWarrantyRecordContractInfoServiceInstance;
            var result = false;
            long insuranceId = 0;
            if (insuranceOrder == null)
            {
                using (TransactionScope sc = new TransactionScope())
                {
                    try
                    {
                        responseResult.OpreateType = OpreateType.Add;

                        insuranceOrderModel.CreateBy = CurrentUser.UserAccount;
                        insuranceOrderModel.OrderStatus = (byte) InsuranceOrderStatus.HadEffective;
                        insuranceOrderModel.OrderNO = CommonMethod.GetNewOrderNo(); //工单号
                        insuranceOrderModel.InsuranceCategoryName =
                            EnumHelper.Instance.GetDescription(typeof (InsuranceProductCategory),
                                insuranceOrderModel.InsuranceCategory); //险种名称
                        insuranceOrderModel.InsuranceCategory = insuranceOrderModel.InsuranceCategory; //险种ID
                        insuranceOrderModel.LastModifyBy = CurrentUser.UserAccount;
                        insuranceOrderModel.LastModifyTime = DateTime.Now;
                        insuranceOrderModel.Price = 0; //默认为0
                        insuranceOrderModel.BuyType = (byte) InsuranceBuyType.NonActivationCodeBuy; //非激活购买
                        insuranceOrderModel.Effective = true; //生效
                        insuranceOrderModel.WaitDays = 0;
                        insuranceOrderModel.CertificateNO = insuranceOrderModel.CertificateNO.Trim() ?? "";
                        insuranceOrderModel.CreateOrderTime = insuranceOrderModel.CreateOrderTime > DateTime.MinValue
                            ? insuranceOrderModel.CreateOrderTime
                            : DateTime.Now;
                        insuranceOrderModel.ProductBrandName = insuranceOrderModel.ProductBrandName ?? "";
                        insuranceOrderModel.ProductModelName = insuranceOrderModel.ProductModelName ?? "";
                        if (insuranceOrderModel.ServiceStartTime != null)
                        {
                            insuranceOrderModel.EffectiveDate =
                                insuranceOrderModel.ServiceStartTime.Value.AddDays(insuranceOrderModel.WaitDays);
                            if (insuranceOrderModel.ServiceEndTime != null)
                                insuranceOrderModel.PolicyPeriod =
                                    (int)
                                        (insuranceOrderModel.ServiceEndTime.Value -
                                         insuranceOrderModel.ServiceStartTime.Value).TotalDays + 1;
                        }

                        insuranceOrderModel.PolicyPeriodUnit = (byte) InsuranceOrderPeriodUnit.Day;
                        insuranceOrderModel.OrderFromType = (byte) InsuranceOrderFromType.FromNoInsuranceIWR;
                        insuranceOrderModel.CertificateType = insuranceOrderModel.CertificateType;
                        insuranceOrderModel.UserName = insuranceOrderModel.UserName;
                        insuranceOrderModel.UserPhone = insuranceOrderModel.UserPhone;
                        insuranceOrderModel.ProductBrandId = insuranceOrderModel.ProductBrandId;
                        insuranceOrderModel.ProductModelId = insuranceOrderModel.ProductModelId;
                        insuranceOrderModel.ProductTypeId = insuranceOrderModel.ProductTypeId;
                        insuranceOrderModel.ProductTypeName =
                            EnumHelper.Instance.GetDescription(typeof (InsuranceOrderDevice),
                                insuranceOrderModel.ProductTypeId);
                        insuranceOrderModel.ThirdOrderNO = insuranceOrderModel.ThirdUniqueNumber;
                        insuranceOrderModel.InsuranceProductID = insuranceOrderModel.InsuranceProductID; //基础产品ID
                        insuranceOrderModel.SellerInsuranceProductID = insuranceOrderModel.SellerInsuranceProductID;
                            //销售商产品ID
                        insuranceOrderModel.DeviceType = insuranceOrderModel.DeviceType;
                        insuranceOrderModel.EquipmentPrice = 0; //设备价格
                        insuranceId = ServiceFactory.InsuranceOrderServiceInstance.AddEntities(insuranceOrderModel).ID;
                        responseResult.Success = insuranceId > 0;
                        sc.Complete();
                    }
                    catch (Exception ex)
                    {
                        sc.Dispose();
                    }
                    if (!responseResult.Success)
                    {
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("CreateNoInsuranceOrderIWR");
                    }
                }
            }
            else
            {
                using (TransactionScope sc = new TransactionScope())
                {
                    try
                    {
                        responseResult.OpreateType = OpreateType.Update;

                        insuranceId = insuranceOrder.ID;

                        insuranceOrder.LastModifyBy = CurrentUser.UserAccount;
                        insuranceOrder.LastModifyTime = DateTime.Now;
                        insuranceOrder.InsuranceCategory = insuranceOrderModel.InsuranceCategory;
                        insuranceOrder.InsuranceCategoryName =
                            EnumHelper.Instance.GetDescription(typeof (InsuranceProductCategory),
                                insuranceOrderModel.InsuranceCategory);
                        insuranceOrder.ProductName = EnumHelper.Instance.GetDescription(typeof (InsuranceOrderDevice),
                            insuranceOrderModel.ProductTypeId);
                        insuranceOrder.ProductTypeId = insuranceOrderModel.ProductTypeId;
                        insuranceOrder.CertificateType = insuranceOrderModel.CertificateType;
                        insuranceOrder.InsuranceCompanyBranch = insuranceOrderModel.InsuranceCompanyBranch;
                        insuranceOrder.DeviceType = insuranceOrderModel.DeviceType;
                        insuranceOrder.ThirdOrderNO = insuranceOrderModel.ThirdUniqueNumber;
                        insuranceOrder.ThirdUniqueNumber = insuranceOrderModel.ThirdUniqueNumber;
                        insuranceOrder.ProductBrandId = insuranceOrderModel.ProductBrandId;
                        insuranceOrderModel.ProductTypeId = insuranceOrderModel.ProductTypeId;
                        insuranceOrderModel.ProductTypeName =
                            EnumHelper.Instance.GetDescription(typeof (InsuranceOrderDevice),
                                insuranceOrderModel.ProductTypeId);
                        insuranceOrder.ProductModelId = insuranceOrderModel.ProductModelId;
                        insuranceOrder.IMEI = insuranceOrderModel.IMEI;
                        insuranceOrder.UserName = insuranceOrderModel.UserName;
                        insuranceOrder.CreateOrderTime = insuranceOrderModel.CreateOrderTime > DateTime.MinValue
                            ? insuranceOrderModel.CreateOrderTime
                            : DateTime.Now;
                        insuranceOrder.UserPhone = insuranceOrderModel.UserPhone.Trim();
                        if (insuranceOrderModel.ServiceStartTime != null)
                        {
                            insuranceOrder.EffectiveDate =
                                insuranceOrderModel.ServiceStartTime.Value.AddDays(insuranceOrderModel.WaitDays);
                            if (insuranceOrderModel.ServiceEndTime != null)
                            {
                                insuranceOrder.PolicyPeriod =
                                    (int)
                                        (insuranceOrderModel.ServiceEndTime.Value -
                                         insuranceOrderModel.ServiceStartTime.Value).TotalDays + 1;
                            }
                        }
                        insuranceOrder.CertificateNO = insuranceOrderModel.CertificateNO.Trim() ?? "";
                        insuranceOrder.ProductBrandName = insuranceOrderModel.ProductBrandName ?? "";
                        insuranceOrder.ProductModelName = insuranceOrderModel.ProductModelName ?? "";
                        insuranceOrder.InsuredAmount = insuranceOrderModel.InsuredAmount;
                        responseResult.Success =
                            ServiceFactory.InsuranceOrderServiceInstance.UpdateEntities(insuranceOrder);
                        sc.Complete();
                    }
                    catch (Exception ex)
                    {
                        sc.Dispose();
                    }
                }
            }
            if (responseResult.Success)//先创建保单，再新建案件
            {
                var insuranceWarrantyRecordController = new InsuranceWarrantyRecordController();
                responseResult.OpreateType = OpreateType.Add;
                var iwrEntiry = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByInsuranceOrderId(insuranceId).FirstOrDefault(c => c.Status != (byte)InsuranceWarrantyStatus.Canceled && c.Status != (byte)InsuranceWarrantyStatus.Refuse);//已取消报案和拒赔的可以再次报案
                long id=0;
                if (iwrEntiry == null)
                {
                    // 先记录日志
                   // insuranceWarrantyRecordController.WriteOperateLog(iwrEntiry, iwRecord);
                    iwrEntiry = new InsuranceWarrantyRecord
                    {
                        InsuranceOrderId = insuranceId,
                        Reporter = iwRecord.Reporter,
                        ReporterPhone = iwRecord.ReporterPhone,
                        ExpectAccidentDate = iwRecord.ExpectAccidentDate > DateTime.MinValue ? iwRecord.ExpectAccidentDate : DateTime.Now,
                        Remark = iwRecord.Remark,
                        WarrantyRecordNo = CommonMethod.GetTimeStamp(),
                        CreateTime = DateTime.Now,
                        CreateBy = insuranceOrderModel.LastModifyBy = CurrentUser.UserAccount,
                        LastModifyBy = CurrentUser.UserAccount,
                        LastModifyTime = DateTime.Now,
                        InsuranceCompanyLossAdjusterName = iwRecord.InsuranceCompanyLossAdjusterName,
                        Status = (byte)InsuranceWarrantyStatus.Created,
                        SystemServiceUserId = CurrentUser.ID
                    };
                    id = ServiceFactory.InsuranceWarrantyRecordServiceInstance.AddEntities(iwrEntiry).ID;
                    responseResult.Success = id > 0;
                    if (!responseResult.Success)
                    {
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("CreateNoInsuranceOrderIWR");
                    }                     
                }
                else
                {
                    responseResult.OpreateType = OpreateType.Update;
                    iwrEntiry.Reporter = iwRecord.Reporter;
                    iwrEntiry.ReporterPhone = iwRecord.ReporterPhone;
                    iwrEntiry.ExpectAccidentDate = iwRecord.ExpectAccidentDate > DateTime.MinValue ? iwRecord.ExpectAccidentDate : DateTime.Now;
                    iwrEntiry.Remark = iwRecord.Remark;
                    iwrEntiry.LastModifyBy = CurrentUser.UserAccount;
                    iwrEntiry.LastModifyTime = DateTime.Now;
                    iwrEntiry.InsuranceCompanyLossAdjusterName = iwRecord.InsuranceCompanyLossAdjusterName;
                    responseResult.Success = ServiceFactory.InsuranceWarrantyRecordServiceInstance.UpdateEntities(iwrEntiry);
                    id = iwrEntiry.ID;
                }
                responseResult.Success = contractInfoServ.AddInsuranceWarrantyRecordContractInfo(id, insuranceWarrantyRecordContractInfo, CurrentUser.UserAccount);
            }
            TempData["ResponseResult"] = responseResult;
            return responseResult.Success ? RedirectToAction("Index", "ToBeMaintainWorkOrder"):RedirectToAction("CreateNoInsuranceOrderIWR");
        }
        #endregion

        #region 获取服务项目
        [HttpPost]
        public JsonResult GetServiceProject(InsuranceWarrantyRecordModel model)
        {
            var total = 0;
            var list = (from cell in ServiceFactory.CellPhoneServiceProjectServiceInstance.LoadEntities(n => true)
                join a in ServiceFactory.ServiceProjectServiceInstance.LoadEntities(n => n.IsAvailable) on
                    cell.ServiceProjectId equals a.ID into temp
                from e in temp.DefaultIfEmpty()
                select new
                {
                   e.UnitInstruction,
                   e.ProjectName,
                   e.ID,
                   e.Price,
                   e.ServiceProductType
                }).ToList();
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}